package me.keiwu.admin.domain;

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;

import javax.persistence.Column;
import javax.persistence.MappedSuperclass;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * Created by kei on 27/10/2017.
 */
@MappedSuperclass
@Data
public abstract class AbstractBaseEntity implements Serializable {

    @CreatedBy
    @Column(name = "created_by", length = 50, updatable = false)
    @JsonIgnore
    private String createdBy;

    @CreatedDate
    @Column(name="created_date", columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
    @JsonIgnore
    private Date createdDate;

    @LastModifiedBy
    @Column(name = "last_modified_by", length = 50)
    @JsonIgnore
    private String lastModifiedBy;

    @LastModifiedDate
    @Column(name="last_modified_date", columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
    @JsonIgnore
    private Date lastModifiedDate;


    /**
     * 用于更新操作
     * @param mewEntity传入的新的值
     * @return
     */
    public AbstractBaseEntity merge(AbstractBaseEntity mewEntity){
        Field[] fields = mewEntity.getClass().getDeclaredFields();
        for(int i=0; i<fields.length; i++){

            Object newValue =  getFieldValueByName(fields[i], mewEntity);

            if(newValue != null){
                setFieldValueByName(fields[i].getName(), this, newValue);
            }

        }
        return this;
    }

    private Object getFieldValueByName(Field field, Object obj) {
        try {
            field.setAccessible(true);
            Object value = field.get(obj);
            field.setAccessible(false);
            return value;
        } catch (Exception e) {
            return null;
        }
    }

    private boolean setFieldValueByName(String fieldName, Object obj, Object value) {
        try {
            Field field = obj.getClass().getDeclaredField(fieldName);
            field.setAccessible(true);
            field.set(obj, value);
            field.setAccessible(false);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
